package com.fanjia.taobao.log.service.impl;

import com.fanjia.taobao.log.aop.Log;
import com.fanjia.taobao.log.dao.MyLogDao;
import com.fanjia.taobao.log.entity.MyLog;
import com.fanjia.taobao.log.service.MyLogService;
import com.github.pagehelper.PageHelper;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.reflect.MethodSignature;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.lang.reflect.Method;
import java.util.List;

/**
 * 日志表(MyLog)表服务实现类
 *
 * @author fanjia
 * @since 2021-04-23 08:31:17
 */
@Service("myLogService")
@Transactional
public class MyLogServiceImpl implements MyLogService {
    @Autowired
    private MyLogDao logDao ;


    @Override
    public void save(String userName, String browser, String ip, ProceedingJoinPoint joinPoint, MyLog myLog) {
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Method method = signature.getMethod();
        Log log = method.getAnnotation(Log.class);
        // 方法路径
        String methodName = joinPoint.getTarget().getClass().getName()+"."+signature.getName()+"()";
        StringBuilder params = new StringBuilder("{");
        //参数值
        Object[] argValues = joinPoint.getArgs();
        //参数名称
        String[] argNames = ((MethodSignature)joinPoint.getSignature()).getParameterNames();
        if(argValues != null){
            for (int i = 0; i < argValues.length; i++) {
                params.append(" ").append(argNames[i]).append(": ").append(argValues[i]);
            }
        }
        // 描述
        if (myLog != null) {
            myLog.setDescription(log.value());
        }
        assert myLog != null;
        myLog.setIp(ip);
        String loginPath = "login";
        if(loginPath.equals(signature.getName())){
            try {
                assert argValues != null;
                userName = new JSONObject(argValues[0]).get("userName").toString();
            }catch (Exception e){
                e.printStackTrace();
            }
        }
        myLog.setMethod(methodName);
        myLog.setUserName(userName);
        myLog.setParams(params.toString() + " }");
        myLog.setBrowser(browser);
        logDao.insert(myLog);
    }

    @Override
    public List<MyLog> query(MyLog myLog, int pageNum, int pageSize) {
        PageHelper.startPage(pageNum,pageSize);
        return logDao.query(myLog);
    }

    @Override
    public int queryCount(MyLog myLog) {
        List<MyLog> myLogList = logDao.query(myLog);
        return myLogList.size();
    }

    @Override
    @Log("删除日志")
    public int delete(int id) {
        return logDao.delete(id);
    }
}